from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    def get(self, request):
        # 1查寻所有省份
        province_list = cache.get('provinces')
        if province_list is None:

            try:
                provinces = Area.objects.filter(parent=None)

                # 2 转换为字典
                # {code:0,erromsg:'ok' ,"province_list":[{"id":id,"name":xxx},{"id":id,"name":xxx},{"id":id,"name":xxx}]}
                province_list = []
                for province in provinces:
                    province_list.append({"id": province.id, "name": province.name})

                cache.set("provinces", province_list, 3600 * 24)
            except Exception as e:
                print(e)
                return http.JsonResponse({"code": 400, "errmsg": "查询失败"})

            # 3 返回响应
        return http.JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class SubAreaView(View):

    def get(self, request, id):
        sub_data = cache.get("sub_areas%s" % id)
        if sub_data is None:
            try:
                # 1获取id 2根据id查询省或者市的对象
                parent_obj = Area.objects.get(id=id)
                # 3获取省或者市下一级的所有数据
                sub_objs = parent_obj.subs.all()
                # print(sub_objs)
                # 4 转为字典
                subs = []
                for sub in sub_objs:
                    subs.append({"id": sub.id, "name": sub.name})
                    # print(sub.name)

                sub_data = {"id": id, "name": parent_obj.name, "subs": subs}
                cache.set("sub_areas%s" % id, sub_data, 3600 * 24)
            except Exception as e:
                print(e)
                return http.JsonResponse({"code": 400, "errmsg": "查询失败"})

        # 5 返回数据
        return http.JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
